package com.tpyule.tpclass.service.impl;

import com.tpyule.tpclass.dao.EvaluationDao;
import com.tpyule.tpclass.entity.bo.CourseEvaluationRateBo;
import com.tpyule.tpclass.entity.bo.EvaluationDetailBo;
import com.tpyule.tpclass.entity.dto.EvaluationQueryDto;
import com.tpyule.tpclass.entity.pojo.Course;
import com.tpyule.tpclass.entity.pojo.Evaluation;
import com.tpyule.tpclass.service.CourseService;
import com.tpyule.tpclass.service.EvaluationService;
import com.tpyule.tpclass.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @author zzz
 * @version 1.0
 * @date 2020/4/18 19:42
 */
@Service
public class EvaluationServiceImpl implements EvaluationService {
    @Autowired
    EvaluationDao evaluationDao;
    @Autowired
    CourseService courseService;
    @Override
    public int addEvaluation(Evaluation evaluation) {
        int result = -1;
        if (evaluation!=null){
            if (evaluation.getRate1()==0 && evaluation.getRate2()==0 && evaluation.getRate3()==0){
                evaluation.setRate1(10);
                evaluation.setRate2(10);
                evaluation.setRate3(10);
            }else {
                evaluation.setRate1(evaluation.getRate1() * 2);
                evaluation.setRate2(evaluation.getRate2() * 2);
                evaluation.setRate3(evaluation.getRate3() * 2);
            }
            evaluation.setEvaluationId(UUID.randomUUID().toString().toUpperCase());
            result = evaluationDao.addEvaluation(evaluation);
            if(result>0){
                String courseId = evaluation.getCourseId();
                CourseEvaluationRateBo rate = evaluationDao.getRateByCourseId(evaluation.getCourseId());
                Course course = courseService.getCourseById(courseId);
                course.setRate1(NumberUtil.getDouble(rate.getRate1(),1));
                course.setRate2(NumberUtil.getDouble(rate.getRate2(),1));
                course.setRate3(NumberUtil.getDouble(rate.getRate3(),1));
                double overRate = (rate.getRate1()+rate.getRate2()+rate.getRate3())/3;
                course.setRateNumber(rate.getNumber());
                course.setOverallRate(NumberUtil.getDouble(overRate,1));
                courseService.updateCourse(course);
            }
        }
        return  result;
    }

    @Override
    public List<EvaluationDetailBo> getEvaluations(EvaluationQueryDto evaluationQueryDto) {
        return evaluationDao.getEvaluations(evaluationQueryDto);
    }

    @Override
    public CourseEvaluationRateBo getRateByCourseId(String courseId) {
        return evaluationDao.getRateByCourseId(courseId);
    }
}
